package com.example.lt.controller;

import com.example.lt.config.QiNiuConfig;
import com.example.lt.context.BaseContext;
import com.example.lt.context.LocalCache;
import com.example.lt.entity.File;
import com.example.lt.entity.Setting;
import com.example.lt.service.FileService;
import com.example.lt.service.SettingService;
import com.example.lt.util.Result;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author 小涛Tao
 * @Date: 2024/08/05/10:21
 * version 1.0 注释：
 **/
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/joyfulMoments/file")
public class FileController implements InitializingBean {

    private final FileService fileService;

    private final QiNiuConfig qiNiuConfig;

    private final SettingService settingService;

    /**
     * 获取上传文件的token
     * @param type 上传文件的类型，目前没有用到，用于将来做扩展
     * @return
     */
    @GetMapping("/getToken")
    public Result getToken(String type) {
        log.info("获取上传文件的token");
        return Result.ok().data(qiNiuConfig.uploadToken(type));
    }

    /**
     * 保存文件信息到文件表
     * @param fileKey
     * @return
     */
    @PostMapping
    public Result saveFile(String fileKey) {
        log.info("保存上传到 QiNiu 的文件信息到文件表：{}", fileKey);
        final Long fileId = fileService.saveFile(fileKey, BaseContext.get());
        return Result.ok().data(fileId);
    }

    /**
     * 对资源的访问进行重定向，指向真实的url，以达到保护资源的目的
     * @param response 响应体
     * @param fileId 资源文件id
     * @throws IOException
     */
    @GetMapping("/{fileId}")
    public void getUUid(HttpServletResponse response, @PathVariable Long fileId) throws IOException {
        log.info("进行资源重定向：{}", fileId);
        final File file = fileService.getFileTrustUrl(fileId);
        response.setContentType(file.getType()); // 文件的类型
        // 重定向方法 sendRedirect()
        response.sendRedirect(file.getFileKey());
    }


    /**
     * 鉴权接口：提供给 QiNiu 的回源鉴权来调用，进行鉴权功能
     * @param uuid
     * @param response
     * @throws IOException
     */
    @PostMapping("/auth")
    public void auth(@RequestParam(required = false) String uuid, HttpServletResponse response) throws IOException {
        if (uuid != null && LocalCache.containsKey(uuid)) {
            LocalCache.rem(uuid);
            response.sendError(200);
        } else {
            response.sendError(401);
        }
    }


    /**
     * 初始化 LocalCache，往里面添加系统配置参数
     * @throws Exception
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        log.info("初始化LocalCache");
        final Setting setting = settingService.getById(1);
        for (String s : setting.getAllowIp().split(",")) {
            LocalCache.put(s, true);
        }
    }

}
